//
//  AIVoiceResultBean.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/27.
//

import Foundation
//AI 通用回调
class AIChatResultBean : Codable {
    var usage: Usage? = nil
    var choices: [Choices]? = nil
    
    class Usage : Codable {
        var total_tokens: Int64  = 0
    }
    class Choices : Codable {
        var message: Messages? = nil
    }
    class Messages : Codable {
        var content: String? = nil
    }
    
    
    func getReplyStr(_ isDelBracket: Bool = false) -> String {
        if choices?.isEmpty == true {
            return ""
        }
        return deleteAiStr(choices?[0].message?.content ?? "", false)
    }
    
    func getChatStr(_ isDelBracket: Bool = false) -> String {
        return deleteAiStr(choices?[0].message?.content ?? "", false)
    }
    
    func getToken() -> Int64 {
           return usage?.total_tokens ?? 0
    }
}



/// 是否含有AI违禁词
func isAiReplyProhibit(_ str: String?) -> Bool {
    if (str ?? "" ).isEmpty {
        //为空也属于违禁词
        return true
    }
    
    // 从配置获取违禁词列表
    let list =  configManager.getConfig().aiChat.aiReplyProhibit
    
    // 检查是否包含任意违禁词
    if let prohibitedList = list, prohibitedList.contains(where: { str!.contains($0) }) {
        return true
    }
    
    // 检查字数是否小于5
    if str!.count < 5 {
        return true
    }
    
    return false
}

func deleteAiStr(_ text: String, _ isDelBracket: Bool = false) -> String {
    guard !text.isEmpty else {
        return text
    }
    
    var processedText = text
    
    // 删除 <think> 标签及其内容
    if let thinkRegex = try? NSRegularExpression(pattern: "<think>[\\s\\S]*?</think>", options: []) {
        let range = NSRange(location: 0, length: processedText.utf16.count)
        processedText = thinkRegex.stringByReplacingMatches(in: processedText, options: [], range: range, withTemplate: "")
    }
    
    // 去除首尾换行符（保留中间换行）
    processedText = processedText
        .replacingOccurrences(of: "^\\n+", with: "", options: .regularExpression)
        .replacingOccurrences(of: "\\n+$", with: "", options: .regularExpression)
    
    // 删除括号内容（如果需要）
    if isDelBracket {
        if let bracketRegex = try? NSRegularExpression(pattern: "\\([^()]*?\\)|（[^）]*?）", options: []) {
            let range = NSRange(location: 0, length: processedText.utf16.count)
            processedText = bracketRegex.stringByReplacingMatches(in: processedText, options: [], range: range, withTemplate: "")
        }
    }
    
    return processedText
}
